<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="danger" plain @click="addRoleDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表表格 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['botBorder',index1 === 0 ? 'topBorder' : '','vcenter']"
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="removeRight(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'topBorder','vcenter']"
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRight(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="danger"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRight(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center" type="index"></el-table-column>
        <el-table-column align="center" prop="roleName" label="角色管理"></el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              plain
              type="success"
              icon="el-icon-edit"
              @click="showEditRloe(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              plain
              type="warning"
              icon="el-icon-delete"
              @click="removeRole(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              plain
              type="danger"
              icon="el-icon-setting"
              @click="showSettingRole(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleFromClose"
    >
      <el-form
        ref="addRoleFromRef"
        :rules="addRoleFromRules"
        :model="addRoleFrom"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="提示" :visible.sync="editRoleDialogVisible" width="50%" @close="editRoleClose">
      <el-form
        :model="editRoleInfo"
        :rules="editRoleFromRules"
        ref="editRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="setRoleDialogVisible" width="30%" @close="closeRole">
      <el-tree
        ref="treeRef"
        node-key="id"
        :data="rightsList"
        :props="treeProps"
        default-expand-all
        show-checkbox
        :default-checked-keys="rightsKeyArr"
      ></el-tree>
      <span slot="footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 添加角色
      addRoleDialogVisible: false,
      addRoleFrom: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFromRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },

      // 编辑角色
      editRoleDialogVisible: false,
      editRoleInfo: [],
      editRoleFromRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },

      // 控制分配权限对话框显示隐藏
      setRoleDialogVisible: false,
      // 权限数据
      rightsList: {},
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      rightsKeyArr: [],
      roleId: ''
    }
  },
  created() {
    // 调用获取角色列表
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },

    // 关闭添加角色对话框，重置表单
    addRoleFromClose() {
      this.$refs.addRoleFromRef.resetFields()
    },

    // 添加角色
    addRole() {
      this.$refs.addRoleFromRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleFrom)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRolesList()
        this.addRoleDialogVisible = false
      })
    },

    // 点击展示编辑角色对话框，并获取当前角色信息
    async showEditRloe(role) {
      // const { data: res } = await this.$http.get(`roles/${role.id}`)
      // if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.editRoleInfo = res.data
      // this.editRoleDialogVisible = true
      this.editRoleInfo = role
      this.editRoleDialogVisible = true
      console.log(role)
    },

    editRoleClose() {
      this.$refs.editRoleFormRef.resetFields()
    },

    // 编辑角色
    editRole() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`roles/${this.editRoleInfo.id}`, {
          roleName: this.editRoleInfo.roleName,
          roleDesc: this.editRoleInfo.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getRolesList()
        this.editRoleDialogVisible = false
      })
    },

    // 删除角色
    async removeRole(id) {
      const confirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') return this.$message.info('明智的选择')
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.info(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },

    // 移除权限
    async removeRight(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') return this.$message.info('您取消了删除')

      // 执行删除
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      role.children = res.data
    },

    // 使用递归方式 获取到三级权限的 id
    getLeafKey(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getLeafKey(item, arr)
      })
    },

    // 展示分配权限对话框，并获取权限数据
    async showSettingRole(role) {
      this.roleId = role.id
      // 获取数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      this.getLeafKey(role, this.rightsKeyArr)
      // 展示权限对话框
      this.setRoleDialogVisible = true
    },

    // 关闭弹窗，清空rightsKeyArr
    closeRole() {
      this.rightsKeyArr = []
    },

    // 将选中的权限同步到服务器
    async saveRole() {
      // 用 element 提供的方法，获取到全选和半选的 id
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      // 处理成后台所需的格式
      const strId = keys.join(',')

      // 发送请求
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: strId
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}

.topBorder {
  border-top: 1px solid #eee;
}
.botBorder {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
